﻿using System;
using System.Linq;
using System.Collections.Generic;
using Eagles.Base;
using Eagles.DomainService.Model.User;
using Eagles.DomainService.Model.Task;
using Eagles.Interface.Core.Task;
using Eagles.Interface.Configuration;
using Eagles.Interface.DataAccess.Util;
using Eagles.Interface.DataAccess.TaskAccess;
using Eagles.Application.Model;
using Eagles.Application.Model.Enums;
using Eagles.Application.Model.Common;
using Eagles.Application.Model.Task.CreateTask;
using Eagles.Application.Model.Task.RemoveTaskStep;
using Eagles.Application.Model.Task.EditTaskStep;
using Eagles.Application.Model.Task.EditTaskAccept;
using Eagles.Application.Model.Task.EditTaskCancel;
using Eagles.Application.Model.Task.EditTaskComplete;
using Eagles.Application.Model.Task.EditTaskFeedBack;
using Eagles.Application.Model.Task.GetTask;
using Eagles.Application.Model.Task.GetTaskDetail;
using Eagles.Application.Model.Task.GetTaskStep;
using Eagles.Application.Model.Task.GetPublicTask;
using Eagles.Application.Model.Task.GetPublicTaskDetail;

namespace Eagles.DomainService.Core.Task
{
    public class TaskHandler : ITaskHandler
    {
        private readonly ITaskAccess iTaskAccess;
        private readonly IUtil util;
        private readonly IEaglesConfig configuration;

        public TaskHandler(ITaskAccess iTaskAccess, IUtil util, IEaglesConfig configuration)
        {
            this.iTaskAccess = iTaskAccess;
            this.util = util;
            this.configuration = configuration;
        }

        public CreateTaskResponse CreateTask(CreateTaskRequest request)
        {
            var response = new CreateTaskResponse();
            var taskId = 0;
            var fromUser = request.TaskFromUser; //任务发起人
            var toUser = request.TaskToUserId; //任务负责人
            var auditUserId = 0; //活动审核人
            var auditUserName = ""; //活动审核人名称
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            //因跨支部创建支部，任务支部、机构取负责人的机构、支部
            var userInfo = util.GetUserInfo(request.TaskToUserId);
            if (userInfo == null)
                throw new TransactionException(MessageCode.UserNotExists, MessageKey.UserNotExists);
            var fromUserInfo = util.GetUserInfo(fromUser);
            var toUserInfo = util.GetUserInfo(toUser);
            if (fromUserInfo == null && toUserInfo == null)
                throw new TransactionException(MessageCode.UserNotExists, MessageKey.UserNotExists);
            var fromUserName = fromUserInfo.Name;
            var toUserName = toUserInfo.Name;
            //找负责人的上级作为审核人
            var superior = util.GetSuperior(toUser);
            if (superior == null)
                throw new TransactionException(MessageCode.AuditUserNotExists, MessageKey.AuditUserNotExists);
            auditUserId = superior.UserId;
            auditUserName = superior.Name;
            var task = new TbTask
            {
                TaskId = request.TaskId,
                OrgId = userInfo.OrgId,
                BranchId = userInfo.BranchId,
                TaskName = request.TaskName,
                BeginTime = request.TaskBeginDate,
                EndTime = request.TaskEndDate,
                TaskContent = request.TaskContent,
                CreateTime = DateTime.Now,
                FromUser = fromUser,
                FromUserName = fromUserName,
                //-2:初始状态;(上级发给下级的初始状态) -1:下级发起任务;
                Status = fromUser == auditUserId ? -2 : -1,
                CanComment = request.CanComment,
                IsPublic = request.IsPublic,
                CreateType = request.CreateType,
                OrgReview = "-1",
                BranchReview = "-1",
                AuditUserId = auditUserId
            };
            if (request.AttachList != null && request.AttachList.Count > 0)
            {
                var attachList = request.AttachList;
                for (int i = 0; i < attachList.Count; i++)
                {
                    if (i == 0)
                    {
                        task.AttachName1 = attachList[i].AttachName;
                        task.Attach1 = attachList[i].AttachmentDownloadUrl;
                    }
                    else if (i == 1)
                    {
                        task.AttachName2 = attachList[i].AttachName;
                        task.Attach2 = attachList[i].AttachmentDownloadUrl;
                    }
                    else if (i == 2)
                    {
                        task.AttachName3 = attachList[i].AttachName;
                        task.Attach3 = attachList[i].AttachmentDownloadUrl;
                    }
                    else if (i == 3)
                    {
                        task.AttachName4 = attachList[i].AttachName;
                        task.Attach4 = attachList[i].AttachmentDownloadUrl;
                    }
                }
            }
            if (request.TaskId > 0)
            {
                //修改
                var taskInfo = iTaskAccess.GetTaskDetail(request.TaskId, request.AppId);
                if (taskInfo == null)
                    throw new TransactionException(MessageCode.TaskNotExists, MessageKey.TaskNotExists);
                if (!(taskInfo.Status == 0 || taskInfo.Status == -1 || taskInfo.Status == -2 || taskInfo.Status == -9))
                    throw new TransactionException(MessageCode.TaskStatusError, MessageKey.TaskStatusError);
                var result = iTaskAccess.EditTask(task, toUser, toUserName);
                if (result <= 0)
                    throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
                taskId = request.TaskId; //通知消息Id取修改的任务Id
            }
            else
            {
                //新增
                var result = iTaskAccess.CreateTask(task, toUser, toUserName, out taskId);
                if (result <= 0)
                    throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            }
            //发用户通知
            var toUserNotice = new TbUserNotice()
            {
                OrgId = userInfo.OrgId,
                Title = "创建任务",
                Content = configuration.EaglesConfiguration.UserNoticContent
                    .Replace("${toUser}", toUserInfo.Name)
                    .Replace("${fromUser}", fromUserInfo.Name)
                    .Replace("${Action}", "发起了需要您负责的")
                    .Replace("${Content}", "“" + request.TaskName + "”的任务"),
                TargetUrl = string.Format(configuration.EaglesConfiguration.TaskNoticeUrl, userInfo.OrgId, taskId),
                //20:任务发起(上级发给下级) 21:任务申请开始(下级发给上级)
                NewsType = fromUser == auditUserId ? 20 : 21,
                FromUser = fromUser,
                UserId = toUser,
                IsRead = 1,
                CreateTime = DateTime.Now
            };
            util.CreateUserNotice(toUserNotice);
            //如果发起人不是审核人，则给审核人发通知
            if (fromUser != auditUserId)
            {
                var toAuditUserNotice = new TbUserNotice()
                {
                    OrgId = toUserNotice.OrgId,
                    Title = toUserNotice.Title,
                    Content = configuration.EaglesConfiguration.UserNoticContent
                        .Replace("${toUser}", auditUserName)
                        .Replace("${fromUser}", fromUserInfo.Name)
                        .Replace("${Action}", "发起了需要您审核的")
                        .Replace("${Content}", "“" + request.TaskName + "”的任务"),
                    TargetUrl = toUserNotice.TargetUrl,
                    //20:任务发起(上级发给下级) 21:任务申请开始(下级发给上级)
                    NewsType = toUserNotice.NewsType,
                    FromUser = toUserNotice.FromUser,
                    UserId = auditUserId,
                    IsRead = toUserNotice.IsRead,
                    CreateTime = toUserNotice.CreateTime
                };
                util.CreateUserNotice(toAuditUserNotice);
            }
            return response;
        }

        public RemoveTaskStepResponse RemoveTaskStep(RemoveTaskStepRequest request)
        {
            var response = new RemoveTaskStepResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var taskInfo = iTaskAccess.GetTaskDetail(request.TaskId, request.AppId);
            if (taskInfo == null)
                throw new TransactionException(MessageCode.TaskNotExists, MessageKey.TaskNotExists);
            //var stepInfo = iTaskAccess.GetStepExist(request.StepId);
            //if (stepInfo == null)
            //    throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            var result = iTaskAccess.RemoveTaskStep(request.TaskId, request.StepId);
            if (result <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public EditTaskAcceptResponse EditTaskAccept(EditTaskAcceptRequest request)
        {
            var response = new EditTaskAcceptResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var taskInfo = iTaskAccess.GetTaskDetail(request.TaskId, request.AppId);
            if (taskInfo == null)            
                throw new TransactionException(MessageCode.TaskNotExists, MessageKey.TaskNotExists);
            var taskStatus = taskInfo.Status;
            //发用户通知
            var userNotice = new TbUserNotice()
            {
                OrgId = tokens.OrgId,
                TargetUrl = string.Format(configuration.EaglesConfiguration.TaskNoticeUrl, tokens.OrgId, request.TaskId),
                IsRead = 1,
                CreateTime = DateTime.Now
            };
            switch (request.Type)
            {
                //上级审核任务
                case TaskAcceptType.Audit:
                    if (taskStatus != -1)
                        throw new TransactionException(MessageCode.TaskStatusError, MessageKey.TaskStatusError);
                    if (taskInfo.AuditUserId != tokens.UserId)
                        throw new TransactionException(MessageCode.TaskMustAudit, MessageKey.TaskMustAudit);
                    userNotice.Title = "任务审核";
                    userNotice.Content = configuration.EaglesConfiguration.UserNoticContent
                        .Replace("${toUser}", taskInfo.UserName)
                        .Replace("${fromUser}", taskInfo.AuditUserName)
                        .Replace("${Action}", "审核通过了")
                        .Replace("${Content}", "“" + taskInfo.TaskName + "”的任务");
                    userNotice.FromUser = taskInfo.AuditUserId;
                    userNotice.UserId = taskInfo.UserId;
                    userNotice.NewsType = 22; //22 任务审核通过(上级审核任务允许开始)
                    break;
                //下级接受任务
                case TaskAcceptType.Accept:
                    if (taskStatus != -2)
                        throw new TransactionException(MessageCode.TaskStatusError, MessageKey.TaskStatusError);
                    if (taskInfo.UserId != tokens.UserId)
                        throw new TransactionException(MessageCode.TaskMustAccept, MessageKey.TaskMustAccept);
                    break;
                //下级申请完成任务
                case TaskAcceptType.Apply:
                    if (taskStatus != 0)
                        throw new TransactionException(MessageCode.TaskStatusError, MessageKey.TaskStatusError);
                    if (taskInfo.UserId != tokens.UserId)
                        throw new TransactionException(MessageCode.TaskMustApply, MessageKey.TaskMustApply);
                    userNotice.Title = "任务申请完成";
                    userNotice.Content = configuration.EaglesConfiguration.UserNoticContent
                        .Replace("${toUser}", taskInfo.AuditUserName)
                        .Replace("${fromUser}", taskInfo.UserName)
                        .Replace("${Action}", "向您申请完成")
                        .Replace("${Content}", "“" + taskInfo.TaskName + "”的任务");
                    userNotice.FromUser = taskInfo.UserId;
                    userNotice.UserId = taskInfo.AuditUserId;
                    userNotice.NewsType = 25; //25 任务申请完成
                    break;
            }
            var result = iTaskAccess.EditTaskAccept(request.Type, request.TaskId, request.ReviewType);
            if (result <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            if (request.ReviewType == 0)
            {
                //发通知给审核人，如果发起人和审核人不是同一个人，则发起人也需发通知
                if (request.Type == TaskAcceptType.Apply && taskInfo.FromUser != taskInfo.AuditUserId)
                {
                    var fromUserNotice = new TbUserNotice()
                    {
                        OrgId = userNotice.OrgId,
                        TargetUrl = userNotice.TargetUrl,
                        IsRead = userNotice.IsRead,
                        CreateTime = userNotice.CreateTime,
                        Title = userNotice.Title,
                        Content = configuration.EaglesConfiguration.UserNoticContent
                            .Replace("${toUser}", taskInfo.FromUserName)
                            .Replace("${fromUser}", taskInfo.UserName)
                            .Replace("${Action}", "向您申请完成")
                            .Replace("${Content}", "“" + taskInfo.TaskName + "”的任务"),
                        NewsType = userNotice.NewsType,
                        FromUser = userNotice.FromUser,
                        UserId = taskInfo.FromUser
                    };
                    util.CreateUserNotice(fromUserNotice);
                }
                util.CreateUserNotice(userNotice);
            }
            return response;
        }

        public EditTaskCompleteResponse EditTaskComplete(EditTaskCompleteRequest request)
        {
            var response = new EditTaskCompleteResponse();
            var score = 0; //奖励积分
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var taskInfo = iTaskAccess.GetTaskDetail(request.TaskId, request.AppId);
            if (taskInfo == null)
                throw new TransactionException(MessageCode.TaskNotExists, MessageKey.TaskNotExists);
            if (taskInfo.Status != 2)
                throw new TransactionException(MessageCode.TaskStatusError, MessageKey.TaskStatusError);
            if (taskInfo.AuditUserId != tokens.UserId)
                throw new TransactionException(MessageCode.TaskMustComplete, MessageKey.TaskMustComplete);
            //查询任务奖励积分
            var rewardScore = util.RewardScore(taskInfo.OrgId, "20");
            if (rewardScore != null)
                score = rewardScore.Score;
            var result = iTaskAccess.EditTaskComplete(request.TaskId, request.IsPublic, request.CompleteStatus, score, request.Score);
            if (!result)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            //发用户通知
            var userNotice = new TbUserNotice()
            {
                OrgId = tokens.OrgId,
                NewsType = 26, //26 任务审核确认完成
                Title = "任务完成",
                Content = configuration.EaglesConfiguration.UserNoticContent
                    .Replace("${toUser}", taskInfo.UserName)
                    .Replace("${fromUser}", taskInfo.AuditUserName)
                    .Replace("${Action}", "审核通过了")
                    .Replace("${Content}", "“" + taskInfo.TaskName + "”的任务"),
                TargetUrl = string.Format(configuration.EaglesConfiguration.TaskNoticeUrl, tokens.OrgId, request.TaskId),
                FromUser = taskInfo.AuditUserId,
                UserId = taskInfo.UserId,
                IsRead = 1,
                CreateTime = DateTime.Now
            };
            if (score > 0)
            {
                util.EditUserScore(taskInfo.UserId, score); //增加完成任务的人积分
                var scoreLs = new TbUserScoreTrace()
                {
                    OrgId = tokens.OrgId,
                    UserId = taskInfo.UserId,
                    CreateTime = DateTime.Now,
                    Score = score,
                    RewardsType = "0",
                    Comment = "完成任务获得积分",
                    Source = taskInfo.TaskName
                };
                util.CreateScoreLs(scoreLs); //增加积分的人增加积分流水
            }
            if (request.CompleteStatus == 0)
                util.CreateUserNotice(userNotice);
            return response;
        }
        
        public EditTaskStepResponse EditTaskStep(EditTaskStepRequest request)
        {
            var response = new EditTaskStepResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var taskInfo = iTaskAccess.GetTaskDetail(request.TaskId, request.AppId);
            if (taskInfo == null)
                throw new TransactionException(MessageCode.TaskNotExists, MessageKey.TaskNotExists);
            if (taskInfo.Status != 0)
                throw new TransactionException(MessageCode.TaskStatusError, MessageKey.TaskStatusError);
            if (taskInfo.UserId != tokens.UserId)
                throw new TransactionException(MessageCode.TaskMustStep, MessageKey.TaskMustStep);
            if (request.StepList == null && request.StepList.Count < 1)
                throw new TransactionException(MessageCode.TaskStepNull, MessageKey.TaskStepNull);
            if (taskInfo.IsFirstStep == 0)
            {
                //发用户通知 2018 - 9 - 14 订制计划不需要再发通知
                //发用户通知 2018 - 10 - 08 新增订制计划要发通知
                var userNotice = new TbUserNotice()
                {
                    OrgId = tokens.OrgId,
                    NewsType = 23, //23 任务负责人定制计划（新增，修改，删除）
                    Title = "任务制定计划",
                    Content = configuration.EaglesConfiguration.UserNoticContent
                        .Replace("${toUser}", taskInfo.AuditUserName)
                        .Replace("${fromUser}", taskInfo.UserName)
                        .Replace("${Action}", "订制了")
                        .Replace("${Content}", taskInfo.TaskName + "的任务计划"),
                    TargetUrl = string.Format(configuration.EaglesConfiguration.TaskNoticeUrl, tokens.OrgId, request.TaskId),
                    FromUser = taskInfo.UserId,
                    UserId = taskInfo.AuditUserId,
                    IsRead = 1,
                    CreateTime = DateTime.Now
                };
                //发通知给审核人，如果发起人和审核人不是同一个人，则发起人也需发通知
                if (taskInfo.FromUser != taskInfo.AuditUserId)
                {
                    var fromUserNotice = new TbUserNotice()
                    {
                        OrgId = userNotice.OrgId,
                        TargetUrl = userNotice.TargetUrl,
                        IsRead = userNotice.IsRead,
                        CreateTime = userNotice.CreateTime,
                        Title = userNotice.Title,
                        Content = configuration.EaglesConfiguration.UserNoticContent
                            .Replace("${toUser}", taskInfo.FromUserName)
                            .Replace("${fromUser}", taskInfo.UserName)
                            .Replace("${Action}", "订制了")
                            .Replace("${Content}", taskInfo.TaskName + "的任务计划"),
                        NewsType = userNotice.NewsType,
                        FromUser = userNotice.FromUser,
                        UserId = taskInfo.FromUser
                    };
                    util.CreateUserNotice(fromUserNotice);
                }
                util.CreateUserNotice(userNotice);
            }
            //全量删除、新增
            iTaskAccess.RemoveTaskStep(request.TaskId, 0);
            foreach (var step in request.StepList)
            {
                var taskStep = new TbUserTaskStep
                {
                    StepId = step.StepId,
                    StepName = step.StepName,
                    OrgId = tokens.OrgId,
                    BranchId = tokens.BranchId,
                    TaskId = request.TaskId,
                    UserId = tokens.UserId,
                    CreateTime = DateTime.Now,
                    PersonCharge = step.PersonCharge,
                    CompleteStatus = step.CompleteStatus
                };
                iTaskAccess.EditTaskStep(taskStep);
            }
            iTaskAccess.EditTaskCompletePercent(request.TaskId, request.CompletePercent);
            return response;
        }

        public EditTaskFeedBackResponse EditTaskFeedBack(EditTaskFeedBackRequest request)
        {
            var response = new EditTaskFeedBackResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var taskInfo = iTaskAccess.GetTaskDetail(request.TaskId, request.AppId);
            if (taskInfo == null)
                throw new TransactionException(MessageCode.TaskNotExists, MessageKey.TaskNotExists);
            if (taskInfo.Status != 0)
                throw new TransactionException(MessageCode.TaskStatusError, MessageKey.TaskStatusError);
            //上级发起的活动
            if (taskInfo.UserId != tokens.UserId)
                throw new TransactionException(MessageCode.TaskMustFeedBack, MessageKey.TaskMustFeedBack);
            var userTaskStep = new TbUserTaskStep()
            {
                TaskId = request.TaskId,
                StepId = request.StepId,
                Content = request.Content,
                UpdateTime = DateTime.Now
            };
            if (request.AttachList != null && request.AttachList.Count > 0)
            {
                var attachList = request.AttachList;
                for (int i = 0; i < attachList.Count; i++)
                {
                    if (i == 0)
                    {
                        userTaskStep.AttachName1 = attachList[i].AttachName;
                        userTaskStep.Attach1 = attachList[i].AttachmentDownloadUrl;
                    }
                    else if (i == 1)
                    {
                        userTaskStep.AttachName2 = attachList[i].AttachName;
                        userTaskStep.Attach2 = attachList[i].AttachmentDownloadUrl;
                    }
                    else if (i == 2)
                    {
                        userTaskStep.AttachName3 = attachList[i].AttachName;
                        userTaskStep.Attach3 = attachList[i].AttachmentDownloadUrl;
                    }
                    else if (i == 3)
                    {
                        userTaskStep.AttachName4 = attachList[i].AttachName;
                        userTaskStep.Attach4 = attachList[i].AttachmentDownloadUrl;
                    }
                }
            }
            var result = iTaskAccess.EditTaskFeedBack(userTaskStep);
            if (result <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            //发用户通知
            var userNotice = new TbUserNotice
            {
                OrgId = tokens.OrgId,
                NewsType = 24, //24 任务负责人反馈计划内容（新增，修改）
                Title = "任务反馈",
                Content = configuration.EaglesConfiguration.UserNoticContent
                    .Replace("${toUser}", taskInfo.AuditUserName)
                    .Replace("${fromUser}", taskInfo.UserName)
                    .Replace("${Action}", "反馈了")
                    .Replace("${Content}", "“" + taskInfo.TaskName + "”的任务"),
                TargetUrl = string.Format(configuration.EaglesConfiguration.TaskNoticeUrl, tokens.OrgId, request.TaskId),
                FromUser = taskInfo.UserId,
                UserId = taskInfo.AuditUserId,
                IsRead = 1,
                CreateTime = DateTime.Now
            };
            //发通知给审核人，如果发起人和审核人不是同一个人，则发起人也需发通知
            if (taskInfo.FromUser != taskInfo.AuditUserId)
            {
                var fromUserNotice = new TbUserNotice()
                {
                    OrgId = userNotice.OrgId,
                    TargetUrl = userNotice.TargetUrl,
                    IsRead = userNotice.IsRead,
                    CreateTime = userNotice.CreateTime,
                    Title = userNotice.Title,
                    Content = configuration.EaglesConfiguration.UserNoticContent
                        .Replace("${toUser}", taskInfo.FromUserName)
                        .Replace("${fromUser}", taskInfo.UserName)
                        .Replace("${Action}", "反馈了")
                        .Replace("${Content}", "“" + taskInfo.TaskName + "”的任务"),
                    NewsType = userNotice.NewsType,
                    FromUser = userNotice.FromUser,
                    UserId = taskInfo.FromUser
                };
                util.CreateUserNotice(fromUserNotice);
            }
            util.CreateUserNotice(userNotice);
            return response;
        }

        public EditTaskCancelResponse EditTaskCancel(EditTaskCancelRequest request)
        {
            var response = new EditTaskCancelResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var taskInfo = iTaskAccess.GetTaskDetail(request.TaskId, request.AppId);
            if (taskInfo == null)
                throw new TransactionException(MessageCode.TaskNotExists, MessageKey.TaskNotExists);
            if (taskInfo.FromUser != tokens.UserId)
                throw new TransactionException(MessageCode.TaskMustCancel, MessageKey.TaskMustCancel);

            bool canUpdate = false;
            //发起人是上级
            if (taskInfo.FromUser == taskInfo.AuditUserId && taskInfo.Status == -2)
            {
                canUpdate = true;
            }
            else if (taskInfo.FromUser == taskInfo.UserId && taskInfo.Status == -1)
            {
                //下级
                canUpdate = true;
            }
            else if (taskInfo.FromUser != taskInfo.UserId && taskInfo.FromUser != taskInfo.AuditUserId && taskInfo.Status == -1)
            {
                //跨支部
                canUpdate = true;
            }

            if (!canUpdate)
            {
                throw new TransactionException(MessageCode.TaskStatusError, MessageKey.TaskStatusError);
            }
            
            var result = iTaskAccess.EditActivityCancel(request.TaskId);
            if (result <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetTaskStepResponse GetTaskStep(GetTaskStepRequest request)
        {
            var response = new GetTaskStepResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var result = iTaskAccess.GetTaskStep(request.TaskId);
            response.StepList = result?.Select(x => new ResStep
            {
                StepId = x.StepId,
                StepName = x.StepName,
                Content = string.IsNullOrEmpty(x.Content) ? "" : x.Content,
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd"),
                PersonCharge = x.PersonCharge,
                CompleteStatus = x.CompleteStatus,
                AttachList = new List<Attachment>()
                {
                    new Attachment() { AttachName = x.AttachName1, AttachmentDownloadUrl = x.Attach1 },
                    new Attachment() { AttachName = x.AttachName2, AttachmentDownloadUrl = x.Attach2 },
                    new Attachment() { AttachName = x.AttachName3, AttachmentDownloadUrl = x.Attach3 },
                    new Attachment() { AttachName = x.AttachName4, AttachmentDownloadUrl = x.Attach4 }
                }
            }).ToList();
            if (result == null || result.Count <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetTaskResponse GetTask(GetTaskRequest request)
        {
            var response = new GetTaskResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var result = iTaskAccess.GetTask(request.TaskType, request.UserId, request.PageIndex, request.PageSize);
            response.TaskList = result?.Select(x => new Application.Model.Common.Task
            {
                TaskId = x.TaskId,
                TaskeName = x.TaskName,
                TaskContent = x.TaskContent,
                TaskStatus = x.Status,
                TaskDate = x.BeginTime.ToString("yyyy-MM-dd"),
                TaskFromUser = x.FromUser,
                TaskFromUserName = x.FromUserName,
                TaskToUser = x.UserId,
                TaskToUserName = x.UserName
            }).ToList();
            if (result == null || result.Count <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetTaskDetailResponse GetTaskDetail(GetTaskDetailRequest request)
        {
            var response = new GetTaskDetailResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var result = iTaskAccess.GetTaskDetail(request.TaskId, request.AppId);
            if (result != null)
            {
                response.TaskId = result.TaskId;
                response.TaskName = result.TaskName;
                response.TaskContent = result.TaskContent;
                response.TaskStatus = result.Status;
                response.TaskBeginDate = result.BeginTime.ToString("yyyy-MM-dd HH:mm:ss");
                response.TaskEndDate = result.EndTime.ToString("yyyy-MM-dd HH:mm:ss");
                response.CreateTime = result.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                response.Score = result.Score;
                response.TaskFounder = result.FromUser;
                response.InitiateUserId = result.FromUser;
                response.InitiateUserName = result.FromUserName;
                response.AcceptUserId = result.UserId;
                response.AcceptUserName = result.UserName;
                response.AuditUserId = result.AuditUserId;
                response.AuditUserName = result.AuditUserName;
                response.CreateType = result.CreateType;
              
                if (result.FromUser == tokens.UserId)
                {
                    //发起人是上级
                    if (result.FromUser == result.AuditUserId && result.Status == -2)
                    {
                        response.IsUpdate = true;
                    }
                    else if(result.FromUser==result.UserId&&result.Status==-1)
                    {
                        //下级
                        response.IsUpdate = true;
                    }
                    else if(result.FromUser!=result.UserId&&result.FromUser!=result.AuditUserId&&result.Status==-1)
                    {
                        //跨支部
                        response.IsUpdate = true;
                    }
                }
                else
                {
                    response.IsUpdate = false;
                }

                //var superior = util.GetSuperior(result.UserId);
                //if (superior == null)
                //    throw new TransactionException(MessageCode.AuditUserNotExists, MessageKey.AuditUserNotExists);
                ////发起人=审核人 发起人就是上级
                //if (superior.UserId == result.FromUser && result.Status == -2)
                //    response.IsUpdate = true;
                ////发起人!=审核人 视作发起人是下级
                //else if (superior.UserId != result.AuditUserId && result.Status == -1)
                //    response.IsUpdate = true;

                response.AttachmentList = new List<Attachment>
                {
                    new Attachment() {AttachName = result.AttachName1, AttachmentDownloadUrl = result.Attach1},
                    new Attachment() {AttachName = result.AttachName2, AttachmentDownloadUrl = result.Attach2},
                    new Attachment() {AttachName = result.AttachName3, AttachmentDownloadUrl = result.Attach3},
                    new Attachment() {AttachName = result.AttachName4, AttachmentDownloadUrl = result.Attach4}
                };
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }
        
        public GetPublicTaskResponse GetPublicTask(GetPublicTaskRequest request)
        {
            var response = new GetPublicTaskResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var token = request.Token;
            var tokens = util.GetUserId(request.Token, 0);
            var branchId = 0;
            if (tokens != null && tokens.UserId > 0)
            {
                branchId = tokens.BranchId;
            }
            var result = iTaskAccess.GetPublicTask(request.AppId, branchId, request.PageIndex, request.PageSize);
            response.TaskList = result?.Select(x => new Application.Model.Common.Task
            {
                TaskId = x.TaskId,
                TaskeName = x.TaskName,
                TaskContent = x.TaskContent,
                TaskStatus = x.Status,
                TaskDate = x.BeginTime.ToString("yyyy-MM-dd"),
                TaskFromUser = x.FromUser,
                TaskFromUserName = x.FromUserName,
                TaskToUser = x.UserId,
                TaskToUserName = x.UserName
            }).ToList();
            if (result == null || result.Count <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetPublicTaskDetailResponse GetPublicTaskDetail(GetPublicTaskDetailRequest request)
        {
            var response = new GetPublicTaskDetailResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var result = iTaskAccess.GetPublicTaskDetail(request.TaskId, request.AppId);
            if (result != null)
            {
                response.TaskId = result.TaskId;
                response.TaskName = result.TaskName;
                response.TaskContent = result.TaskContent;
                response.TaskStatus = result.Status;
                response.TaskBeginDate = result.BeginTime.ToString("yyyy-MM-dd HH:mm:ss");
                response.TaskEndDate = result.EndTime.ToString("yyyy-MM-dd HH:mm:ss");
                response.CreateTime = result.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                response.Score = result.Score;
                response.TaskFounder = result.FromUser;
                response.InitiateUserId = result.FromUser;
                response.InitiateUserName = result.FromUserName;
                response.AcceptUserId = result.UserId;
                response.AcceptUserName = result.UserName;
                response.AuditUserId = result.AuditUserId;
                response.AuditUserName = result.AuditUserName;
                response.CreateType = result.CreateType;
                response.ViewCount = result.ViewCount;
                response.AttachmentList = new List<Attachment>
                {
                    new Attachment() {AttachName = result.AttachName1, AttachmentDownloadUrl = result.Attach1},
                    new Attachment() {AttachName = result.AttachName2, AttachmentDownloadUrl = result.Attach2},
                    new Attachment() {AttachName = result.AttachName3, AttachmentDownloadUrl = result.Attach3},
                    new Attachment() {AttachName = result.AttachName4, AttachmentDownloadUrl = result.Attach4}
                };
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }
    }
}